<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-title">
        <h1>不然影院</h1>
        <p>探索光影世界，发现精彩瞬间</p>
      </div>
      <div class="login-card">
        <h2>登录</h2>

        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="0px">
          <el-form-item prop="loginType">
            <el-radio-group v-model="loginForm.loginType" class="login-type-switch">
              <el-radio-button label="user">用户登录</el-radio-button>
              <el-radio-button label="admin">管理员登录</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleLogin" :loading="loading" style="width: 100%;">
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <div v-if="loginForm.loginType === 'user'" class="form-footer">
          <p>
            还没有账号？
            <router-link to="/register">立即注册</router-link>
          </p>
        </div>
      </div>
    </div>
    <div class="particles-container"></div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm, ElInput, ElButton, ElCard, ElFormItem, ElRadioGroup, ElRadioButton } from 'element-plus'
import { useUserStore } from '../store/user'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import axios from 'axios'

const userStore = useUserStore()
const router = useRouter()

const loginFormRef = ref<FormInstance>()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  loginType: 'user',
})

const loginRules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  loginType: [{ required: true, message: '请选择登录类型', trigger: 'change' }],
})

onMounted(() => {
  // 根据默认登录类型读取用户名
  const lastUsernameKey = loginForm.loginType === 'user' ? 'lastUserUsername' : 'lastAdminUsername';
  const lastUsername = localStorage.getItem(lastUsernameKey);
  if (lastUsername) {
      loginForm.username = lastUsername;
  }

  // 创建背景动画效果 - Commented out as requested
  // createParticles();
})

// 监听登录类型变化，加载对应的用户名
watch(() => loginForm.loginType, (newLoginType) => {
  const lastUsernameKey = newLoginType === 'user' ? 'lastUserUsername' : 'lastAdminUsername';
  const lastUsername = localStorage.getItem(lastUsernameKey);
  loginForm.username = lastUsername || ''; // 如果没有记录则清空
});

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await axios.post('http://localhost:8080/api/auth/login', {
          username: loginForm.username,
          password: loginForm.password,
          loginType: loginForm.loginType,
        });

        if (response.data && response.data.token) {
          const { token, userId, username, role } = response.data;
          // 调用 Pinia store action 进行登录
          userStore.login(token, { id: userId, username, role });

          // 登录成功后，根据登录类型保存用户名
          const lastUsernameKey = loginForm.loginType === 'user' ? 'lastUserUsername' : 'lastAdminUsername';
          localStorage.setItem(lastUsernameKey, loginForm.username);

          // 修改：设置提示消息停留时间为 1 秒
          ElMessage.success({ message: '登录成功', duration: 1000 });

          // 根据角色跳转
          if (role === 'ROLE_ADMIN') {
            router.push('/admin'); // 管理员跳转到后台管理页
          } else {
            router.push('/home'); // 修复：普通用户直接跳转到 /home，避免 / 重定向问题
          }
        } else {
          // 后端未返回 token 或预期的数据结构
          ElMessage.error(response.data?.message || '登录失败，响应格式错误');
        }
      } catch (error: any) { // 捕获 axios 错误
        console.error('登录请求失败:', error);
        if (error.response) {
          // 请求发出，服务器响应了状态码，但不是 2xx
          ElMessage.error(error.response.data || '登录失败，请检查用户名和密码');
        } else if (error.request) {
          // 请求发出，但没有收到响应
          ElMessage.error('登录失败，无法连接到服务器');
        } else {
          // 在设置请求时触发了一个错误
          ElMessage.error('登录失败，发生未知错误');
        }
      } finally {
        loading.value = false;
      }
    } else {
      console.log('表单验证失败');
    }
  });
};

// 创建背景动态效果 - Commented out
/*
const createParticles = () => {
  const container = document.querySelector('.particles-container');
  if (!container) return;

  for (let i = 0; i < 50; i++) {
    const particle = document.createElement('div');
    particle.classList.add('particle');

    // 随机大小
    const size = Math.random() * 5 + 1;
    particle.style.width = `${size}px`;
    particle.style.height = `${size}px`;

    // 随机位置
    particle.style.left = `${Math.random() * 100}%`;
    particle.style.top = `${Math.random() * 100}%`;

    // 随机透明度
    particle.style.opacity = `${Math.random() * 0.5 + 0.1}`;

    // 随机动画延迟
    particle.style.animationDelay = `${Math.random() * 5}s`;
    particle.style.animationDuration = `${Math.random() * 10 + 10}s`;

    container.appendChild(particle);
  }
}
*/
</script>

<style scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  /* Use the new background image */
  background: url('/login-background.jpg') no-repeat center center;
  background-size: cover; /* Make image cover the container */
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
  text-align: center;
  width: 100%;
  max-width: 420px;
  padding: 0 20px;
}

.login-title {
  margin-bottom: 2rem;
  color: #fff;
  text-shadow: 0 2px 10px rgba(0,0,0,0.3);
}

.login-title h1 {
  font-size: 2.8rem;
  margin-bottom: 0.8rem;
  font-weight: 600;
  letter-spacing: 1px;
}

.login-title p {
  font-size: 1.1rem;
  font-weight: 300;
  opacity: 0.9;
}

.login-card {
  width: 100%;
  padding: 30px;
  /* background-color: rgba(255, 255, 255, 0.98); */ /* Original slightly transparent */
  background-color: rgba(255, 255, 255, 0.6); /* Make it more transparent */
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.login-card h2 {
  font-size: 1.6rem;
  color: #333;
  margin-bottom: 25px;
  font-weight: 500;
  text-align: center;
}

.login-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.6); /* Add semi-transparent background */
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #4e6ef2 inset, 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__inner) {
  height: 42px;
  font-size: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-form-item__error) {
  font-size: 13px;
  padding-top: 4px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(to right, #4568dc, #3f51b5);
  border: none;
  box-shadow: 0 4px 12px rgba(79, 114, 205, 0.5);
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(79, 114, 205, 0.6);
  background: linear-gradient(to right, #3a5eca, #3949ab);
}

.login-button:active {
  transform: translateY(0);
}

.form-footer {
  margin-top: 25px;
  text-align: center;
  font-size: 0.9rem;
  color: #555;
}

.form-footer a {
  color: #4568dc;
  text-decoration: none;
  font-weight: 500;
  margin-left: 5px;
  transition: color 0.2s;
}

.form-footer a:hover {
  color: #3a5eca;
  text-decoration: underline;
}

/* 背景动画 - Commented out */
/*
.particles-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.particle {
  position: absolute;
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
  animation: float 15s infinite ease-in-out;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) translateX(0);
  }
  25% {
    transform: translateY(-40px) translateX(20px);
  }
  50% {
    transform: translateY(-80px) translateX(-20px);
  }
  75% {
    transform: translateY(-40px) translateX(-40px);
  }
}
*/

.login-type-switch {
  width: 100%;
  display: flex;
  margin-bottom: 15px;
}

.login-type-switch .el-radio-button {
  flex-grow: 1;
}

.login-type-switch :deep(.el-radio-button__inner) {
  width: 100%;
}

.register-link {
  margin-top: 15px;
  text-align: center;
  font-size: 14px;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>